package com.corpgovernment.common.handler;

import com.ctrip.corp.obt.generic.utils.EncryptUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

/**
 * @author xbqi
 * @date 2023/10/12
 */
public class Sm4DecryptTypeHandler implements TypeHandler<String> {

    private static String KEY = "1234567890123456";

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
            throws SQLException {
        //防止为null时，创建XMLType出现错误
        if (StringUtils.isNotBlank(parameter)) {
            ps.setObject(i, parameter);
        } else {
            ps.setString(i, null);
        }
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        String source = rs.getString(columnName);
        return getDecryptString(source);
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        String source = rs.getString(columnIndex);
        return getDecryptString(source);
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String source = cs.getString(columnIndex);
        return getDecryptString(source);
    }

    private static String getDecryptString(String source) {
        if (StringUtils.isNotBlank(source)) {
            if (Base64.isBase64(source)) {
                return EncryptUtils.sm4Decrypt(source, KEY);
            } else {
                return source;
            }
        } else {
            return null;
        }
    }

}
